<?php

namespace app\service;

use app\model\Device;
use app\model\AlarmNotification;
use app\model\User;
use support\Db;

class AlarmService
{
    private $smsService;
    private $wechatService;

    public function __construct()
    {
        $this->smsService = new SmsService();
        $this->wechatService = new WechatService();
    }

    public function handleDeviceAlarm($deviceId)
    {
        try {
            // 获取设备信息
            $device = Device::find($deviceId);
            if (!$device || $device->alarm <= 0) {
                return;
            }

            // 获取设备关联的用户
            $users = $device->users;

            foreach ($users as $user) {

                $where = [
                    'user_id' => $user->id,
                    'alarm_num' => $device->alarm,
                    'device_id' => $device->id,
                    'notify_status' => 'sent',

                ];

                //todo 同一设备10分钟内只发送一次报警
                $check = AlarmNotification::query()->where($where)->orderBy('id', 'desc')->first();

                // var_dump($check);

                if ($check && (time() - $check->last_send_at) < ini('NOTIFY_DELAY_SECOND', 86400)) {
                    //小于10分钟 暂时不发
                    continue;
                }

                // 创建报警通知记录
                $notification = new AlarmNotification([
                    'device_id' => $device->id,
                    'user_id' => $user->id,
                    'type' => $this->getAlarmType($device->alarm),
                    'alarm_num' => $device->alarm,
                    'message' => $this->generateAlarmMessage($device),
                    'status' => 1,
                    'notify_status' => 'pending'
                ]);

                Db::beginTransaction();

                try {
                    $notification->save();

                    // 发送短信通知
                    if ($user->phone) {
                        $smsSent = $this->smsService->sendAlarmNotification(
                            $user->phone,
                            $device->sn,
                            $notification->message,
                        );
                        $notification->sms_status = $smsSent ? 'sent' : 'failed';
                    }

                    // 发送微信订阅消息
                    if ($user->openid) {
                        $wechatSent = $this->wechatService->sendAlarmNotification(
                            $user->openid,
                            $device->id,
                            $device->sn,
                            $notification->message,
                        );
                        $notification->wechat_status = $wechatSent ? 'sent' : 'failed';
                    }

                    // 更新通知状态
                    $notification->notify_status = 'sent';
                    $notification->last_send_at = time();
                    $notification->save();

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollBack();
                    error_log("Alarm notification failed: " . $e->getMessage());
                    throw $e;
                }
            }
        } catch (\Exception $e) {
            error_log("Alarm handling failed: " . $e->getMessage());
        }
    }

    private function getAlarmType($alarmValue)
    {
        // 根据报警值确定报警类型
        // 这里需要根据你的业务逻辑来实现
        if ($alarmValue > 1) {
            return 2;
        }
        return 1;
    }

    public function generateAlarmMessage($device)
    {

        $arr = [
            1 => '设备漏水故障',
            2 => '水箱液位上限预警',
            3 => '水箱液位下限预警',
            4 => '膜寿命到期预警',
            5 => '水质异常预警',
            6 => '产水率下降预警',
            7 => '水温异常预警',
        ];

        return $arr[$device->alarm] ?? '未知异常';
    }
}
